/**
 * mongodb 连接
 */
// Create a new MongoClient
import { port, mongoConfig } from '../config';
const { url, dbName } = mongoConfig;
const { MongoClient } = require('mongodb');

// mongodb 单例模式创建连接
class Db {
    public static getInstance(callback: any = "") {
        // 单例模式 解决多次实例化 实例不共享的问题
        if (!Db.instance) {
            Db.instance = new Db(callback);
        }
        return Db.instance;
    }
    private static instance: any;
    private static dbClient: any;
    public dbClient: any;
    constructor(callback: any = "") {
        this.connect(callback); // 实例化的时候就连接数据库
    }

    private connect(callback: any) {
        // 连接数据库
        if (!Db.dbClient) {
            // 解决数据库多次连接的问题
            const client = new MongoClient(url, { useUnifiedTopology: true });
            console.log("mongodb connecting...");
            // Use connect method to connect to the Server
            client.connect((err: any) => {
                if (err) {
                    console.log("mongodb connect faild! Please try again!");
                    return;
                }
                const dbClient = client.db(dbName);
                this.dbClient = dbClient;
                Db.dbClient = dbClient;
                console.log("mongodb connect success!");
                const type = typeof callback;
                if (callback && 'function' === type) {
                    callback();
                }
            });
        }
    }
}
export default Db;
module.exports = Db;